/**
 * 
 */
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import model.Bewertung;
import model.Gebot;
import model.GebotsListe;
import db.DbConnection;

public class GebotDAO {

	final String selectGebot = "SELECT * FROM Gebot where BuchID=? ORDER BY Gebot DESC";
	final String selectAll = "SELECT * FROM Gebot ORDER BY Gebot DESC";
	final String insert = "INSERT INTO Gebot VALUES(NULL, ?, ?, ?, ?)";

	public GebotsListe getGeboteByBuchID(int id) throws SQLException {
		Connection con = DbConnection.getInstance();

		PreparedStatement prepstmt = con.prepareStatement(this.selectGebot);
		prepstmt.setInt(1, id);

		GebotsListe gebote = new GebotsListe();
		ResultSet rs = prepstmt.executeQuery();

		while (rs.next()) {
			int ID = rs.getInt("ID");
			int buchID = rs.getInt("BuchID");
			long datum = rs.getLong("Datum");
			float gebot = rs.getFloat("Gebot");
			String kaeufer = rs.getString("Kaeufer");

			gebote.add(new Gebot(ID, buchID, gebot, datum, kaeufer));
		}

		return gebote;
	}

	public boolean saveGebot(Gebot g) throws SQLException {
		Connection con = DbConnection.getInstance();

		PreparedStatement prepstmt = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
		prepstmt.setString(1, g.get_kaeufer());
		prepstmt.setInt(2, g.get_buchID());
		prepstmt.setFloat(3, g.get_gebot());
		prepstmt.setLong(4, g.get_datum());

		if (prepstmt.executeUpdate() == 1) {
			ResultSet rs = prepstmt.getGeneratedKeys();
			rs.next();
			g.set_id(rs.getInt(1));
			return true;
		} else {
			return false;
		}
	}
}
